package private

import (
	"dc-go/global"
	"dc-go/model"
	"errors"
	"time"

	"gorm.io/gorm"
)

type ServiceRole struct{}

func (s *ServiceRole) GetRoleList(requestRoleList model.RequestGetRoleList) (role interface{}, total int64, err error) {
	if requestRoleList.SortBy == "" {
		requestRoleList.SortBy = "id"
		requestRoleList.Desc = false
	}
	pageSize := requestRoleList.PageSize
	offset := requestRoleList.PageSize * (requestRoleList.Page - 1)
	db := global.DcDb.Model(&model.SysRole{})
	var roleList []model.SysRole
	//配置搜索
	if requestRoleList.RoleCode != "" {
		db = db.Where("role_code like ?", "%"+requestRoleList.RoleCode+"%")
	}
	if requestRoleList.RoleName != "" {
		db = db.Where("role_name like ?", "%"+requestRoleList.RoleName+"%")
	}
	err = db.Count(&total).Error
	if err != nil {
		return nil, 0, err
	}
	err = db.Limit(pageSize).Offset(offset).Order(model.OrderByColumn(requestRoleList.SortBy, requestRoleList.Desc)).Find(&roleList).Error
	return roleList, total, err
}

func (s *ServiceRole) EditRole(toEditRole model.SysRole) (err error) {
	var sysRole model.SysRole
	if err = global.DcDb.Where("id = ?", toEditRole.Id).First(&sysRole).Error; err != nil {
		return err
	}
	if *sysRole.Source == "internal" {
		return errors.New("系统内置不允许编辑：" + toEditRole.RoleCode)
	}
	//err = global.DcDb.Updates(&toEditRole).Error
	err = global.DcDb.Save(&toEditRole).Error
	return err
}

func (s *ServiceRole) AddRole(toAddRole model.SysRole) (err error) {
	var role model.SysRole
	if !errors.Is(global.DcDb.Where("role_code = ?", toAddRole.RoleCode).First(&role).Error, gorm.ErrRecordNotFound) {
		return errors.New("此角色已存在：" + toAddRole.RoleCode)
	}
	err = global.DcDb.Create(&toAddRole).Error
	return err
}

func (s *ServiceRole) DeleteRoleById(id uint) (err error) {
	var sysRole model.SysRole
	if err = global.DcDb.Where("id = ?", id).First(&sysRole).Error; err != nil {
		return err
	}
	if *sysRole.Source == "internal" {
		return errors.New("系统内置不允许删除：" + sysRole.RoleCode)
	}
	roleCode := sysRole.RoleCode
	// 删除 sys_role_api 表的权限
	err = global.DcDb.Where("role_code = ?", roleCode).Delete(model.SysRoleApi{}).Error
	if err != nil {
		return err
	}
	// 删除 sys_role 表的数据
	err = global.DcDb.Unscoped().Delete(&sysRole).Error
	if err != nil {
		return err
	}
	// 删除 sys_user_role 表的对应关系
	err = global.DcDb.Where("role_code = ?", roleCode).Delete(&model.SysOrgRole{}).Error
	if err != nil {
		return err
	}
	// 删除 sys_role_menu 表的对应关系
	err = global.DcDb.Where("role_code = ?", roleCode).Delete(&model.SysRoleMenu{}).Error
	if err != nil {
		return err
	}

	// 删除 sys_role_api 表的对应关系
	err = global.DcDb.Where("role_code = ?", roleCode).Delete(&model.SysRoleApi{}).Error
	if err != nil {
		return err
	}

	// TODO: 删除 sys_user_org_role 表的对应关系
	return err
}

func (s *ServiceRole) QueryRoleById(id uint) (roleInfo model.SysRole, err error) {
	var role model.SysRole
	err = global.DcDb.First(&role, "id = ?", id).Error
	return role, err
}

func (s *ServiceRole) GetRoleMenuList(roleCode *model.RequestRoleCode) (roleMenu []model.SysRoleMenu, err error) {
	err = global.DcDb.Where("role_code=?", roleCode.RoleCode).Find(&roleMenu).Error
	return roleMenu, err
}

func (s *ServiceRole) EditRoleMenu(toEditRoleMenu *model.RequestRoleMenuEdit, empeeAcct string) (err error) {
	// var role model.SysRole
	// err = global.DcDb.Where("role_code = ?", toEditRoleMenu.RoleCode).First(&role).Error
	// if err != nil {
	// 	return err
	// }
	var roleMenusBefore []model.SysRoleMenu
	err = global.DcDb.Where("role_code = ?", toEditRoleMenu.RoleCode).Find(&roleMenusBefore).Error
	for _, menuCode := range toEditRoleMenu.MenuCode {
		// var menu model.SysMenu
		// err = global.DcDb.Where("menu_code = ?", menuCode).First(&menu).Error
		// if err != nil {
		// 	return err
		// }
		//如果是新增的菜单，则插入数据
		var isExist bool
		for _, roleMenuBefore := range roleMenusBefore {
			if roleMenuBefore.MenuCode == menuCode {
				isExist = true
				break
			}
		}
		if !isExist {
			var roleMenu model.SysRoleMenu
			roleMenu.RoleCode = toEditRoleMenu.RoleCode
			roleMenu.MenuCode = menuCode
			roleMenu.CreatedBy = empeeAcct
			roleMenu.CreatedAt = time.Now()
			roleMenu.UpdatedBy = empeeAcct
			roleMenu.UpdatedAt = time.Now()
			err = global.DcDb.Create(&roleMenu).Error
			if err != nil {
				return err
			}
		}
	}
	//删除旧的菜单
	for _, roleMenuBefore := range roleMenusBefore {
		var isExist bool
		for _, menuCode := range toEditRoleMenu.MenuCode {
			if roleMenuBefore.MenuCode == menuCode {
				isExist = true
				break
			}
		}
		if !isExist {
			err = global.DcDb.Where("role_code = ? and menu_code = ?", toEditRoleMenu.RoleCode, roleMenuBefore.MenuCode).Delete(&model.SysRoleMenu{}).Error
			if err != nil {
				return err
			}
		}
	}
	return err
}

func (s *ServiceRole) GetRoleApiList(roleCode *model.RequestRoleCode) (api []model.SysRoleApi, err error) {
	var roleApi []model.SysRoleApi
	err = global.DcDb.Where("role_code=?", roleCode.RoleCode).Find(&roleApi).Error
	return roleApi, err
}

func (s *ServiceRole) EditRoleApi(toEditRoleApi *model.RequestEditRoleApi) (err error) {
	err = global.DcDb.Where("role_code = ?", toEditRoleApi.RoleCode).Delete(&model.SysRoleApi{}).Error

	if len(toEditRoleApi.RoleApi) != 0 {
		err = global.DcDb.Model(&model.SysRoleApi{}).Create(&toEditRoleApi.RoleApi).Error
		return err
	}
	return nil
}

// func (s *ServiceRole) EditRoleDeptDataPermission(toEditRoleDeptDataPermission *model.RequestRoleDeptDataPermission) (err error) {
// 	var sysRole model.SysRole
// 	if err = global.DcDb.Where("role_code = ?", toEditRoleDeptDataPermission.RoleCode).First(&sysRole).Error; err != nil {
// 		return err
// 	}
// 	if sysRole.Stable == "yes" {
// 		return errors.New("系统内置不允许编辑：" + toEditRoleDeptDataPermission.RoleCode)
// 	}
// 	sysRole.DeptDataPermissionType = toEditRoleDeptDataPermission.DeptDataPermissionType
// 	sysRole.DeptDataPermissionCustom = toEditRoleDeptDataPermission.DeptDataPermissionCustom
// 	err = global.DcDb.Save(&sysRole).Error
// 	return err
// }
